package com.ramos.kuaixiao.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.ShopTypeBean;
import com.ramos.kuaixiao.ui.SpaceImageDetailActivity;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProductAdapter extends BaseAdapter implements Filterable {
    private static String TAG = "ShopOrderActivity";
    private List<ShopTypeBean.ShopType.ProductInfo> tasklist;
    private Activity activity;
    private ArrayList<ShopTypeBean.ShopType.ProductInfo> mOriginalValues;
    private final Object mLock = new Object();
    private String keyWrold = ""; // 关键字
    UpdateCarListener updateListener;
    Customer mCustomer;
    String custmerId;
    static class ViewHolder {
        TextView name;
        TextView id;
        TextView warehouse;
        TextView price;
        ImageView productImg;
        TextView barcodeText;
        LinearLayout ll_product;
    }

    public ProductAdapter(Activity context, List<ShopTypeBean.ShopType.ProductInfo> hotcourse, Customer customer) {
        this.activity = context;
        this.tasklist = hotcourse;
        mCustomer = customer;
        initImage(tasklist);
        //getWare(tasklist);
    }

    private void initImage(List<ShopTypeBean.ShopType.ProductInfo> tasklist) {
        Product product = new Product(tasklist);
        product.executeOnExecutor(Executors.newCachedThreadPool());

    }

    public void getWare(List<ShopTypeBean.ShopType.ProductInfo> type){
        WareHouse product = new WareHouse(type);
        product.executeOnExecutor(Executors.newCachedThreadPool());
    }

    public void refresh(List<ShopTypeBean.ShopType.ProductInfo> data) {
        tasklist = data;
        initImage(tasklist);
        //getWare(tasklist);
    }

    @Override
    public int getCount() {
        if (tasklist == null) {
            return 0;
        } else {
            return tasklist.size();
        }
    }

    @Override
    public Object getItem(int position) {
        return tasklist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(activity).inflate(R.layout.listitem_product, null);
            holder = new ViewHolder();
            holder.name = (TextView) convertView.findViewById(R.id.brand_name);
            holder.id = (TextView) convertView.findViewById(R.id.brand_id);
            holder.warehouse = (TextView) convertView.findViewById(R.id.brand_warehouse);
            holder.price = (TextView) convertView.findViewById(R.id.brand_price);
            holder.productImg = (ImageView) convertView.findViewById(R.id.productImg);
            holder.barcodeText = (TextView) convertView.findViewById(R.id.barcodeText);
            holder.ll_product = (LinearLayout) convertView.findViewById(R.id.ll_product);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        showText(tasklist.get(position).getProductInfoName(), holder.name);
        showText(tasklist.get(position).getProductInfoId(), holder.id);
        holder.warehouse.setText(tasklist.get(position).getTotal());
        if (StringUtil.isEmpty(tasklist.get(position).getNonTaxSalePrice())) {
            holder.price.setVisibility(View.INVISIBLE);
        } else {
            holder.price.setVisibility(View.VISIBLE);
            holder.price.setText("￥" + tasklist.get(position).getNonTaxSalePrice());
        }
        Log.d("Product", "tasklist.get(position).getIconUrl() " + position + " " + tasklist.get(position).getIconUrl()
                + " " + tasklist.get(position).getProductInfoName() + " " + tasklist.get(position).getProductInfoId()
                + tasklist.get(position).getTotal() + " " + tasklist.get(position).getNonTaxSalePrice());
        Log.d("Product", "tasklist.get(position).getIconUrl() " + position + " " + tasklist.get(position).getIconUrl()
                + " " + tasklist.get(position).getProductInfoName() + " " + tasklist.get(position).getProductInfoId());
        Utils.glideImage(tasklist.get(position).getIconUrl(), holder.productImg);
        final int width = holder.productImg.getWidth();
        final int height = holder.productImg.getHeight();
        final int[] location = new int[2];
        holder.productImg.getLocationOnScreen(location);

        holder.productImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(activity, width, height, location, tasklist.get(position).getIconUrl());
            }
        });
        holder.barcodeText.setText(Utils.getText(tasklist.get(position).getProductBarCode()));
        //getWareAndPrice(tasklist.get(position));
        return convertView;
    }

   class WareHouse extends AsyncTask<String, String, String> {
       private List<ShopTypeBean.ShopType.ProductInfo> productList = new ArrayList<>();

       public WareHouse(List<ShopTypeBean.ShopType.ProductInfo> type) {
           productList = type;
       }

       @Override
       protected String doInBackground(String... params) {
           try {
               for (int i = 0; i < productList.size(); i++) {
                   final ShopTypeBean.ShopType.ProductInfo product = productList.get(i);
                   getWareAndPrice(product);
               }

           } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
           return null;
       }

       @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            //notifyDataSetChanged();
        }
    }

    public void getWareAndPrice(final ShopTypeBean.ShopType.ProductInfo product) {
        try {
            String url = NetUtils.SHOP_INFO;
            if (mCustomer != null && !StringUtil.isEmpty(mCustomer.getId())) {
                custmerId = mCustomer.getId();
            } else {
                custmerId = SharedPreference.getPreferString("id");
            }
            String path = url + "dealerId=test2&productBarCode=" + product.getProductBarCode() + "&productInfoId=" + product.getProductInfoId() + "&custmerId=" + custmerId
                    + "&userId=" + SharedPreference.getPreferString("id");
            Log.d("getWareAndPrice", "path=" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            JSONObject jsonObejct = JSONObject.parseObject(result);
                            JSONObject data = jsonObejct.getJSONObject("data");
                            com.ramos.kuaixiao.entity.Product product1 = JSONObject.parseObject(data.toString(), com.ramos.kuaixiao.entity.Product.class);
                            String singlePrice = product1.getSalePrice();
                            product.setNonTaxSalePrice(singlePrice);
                            Log.d(TAG, "result :singlePrice "+ singlePrice) ;
                            List<com.ramos.kuaixiao.entity.Product.WareInfo> ware = product1.getWareList();
                            Set<Integer> set = new HashSet<>();
                            if(ware != null && ware.size() > 0){
                                for(com.ramos.kuaixiao.entity.Product.WareInfo w : ware){
                                    set.add(w.getCount());
                                }
                                Log.d(TAG, "result :setTotal "+ Collections.max(set)) ;
                                //product.setTotal(Collections.max(set));
                            }
                            //notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getStore(int count) {
        String store;
        if (count == 0) {
            store = "0支";
        } else {
            store = "(" + count + "支)";
        }
        return store;
    }

    private void showImage(Activity actiivty, int width, int height, int[] location, String iconUrl) {
        Intent intent = new Intent(actiivty, SpaceImageDetailActivity.class);
        intent.putExtra("images", iconUrl);
        intent.putExtra("locationX", location[0]);
        intent.putExtra("locationY", location[1]);

        intent.putExtra("width", width);
        intent.putExtra("height", height);
        actiivty.startActivity(intent);
        actiivty.overridePendingTransition(0, 0);
    }

    private void showText(String str, TextView textView) {
        textView.clearComposingText();
        if (!keyWrold.equals("")) {
            String patten = "" + keyWrold;
            Pattern p = Pattern.compile(patten);
            Matcher m = p.matcher(str);
            SpannableString spannableString = new SpannableString(str);
            while (m.find()) {
                if (str.contains(m.group())) {
                    spannableString.setSpan(
                            new ForegroundColorSpan(0xffec8b44), m.start(),
                            m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            textView.setText(spannableString);
        } else {
            textView.setText(str);
        }
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        return filter;
    }

    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            tasklist = (List<ShopTypeBean.ShopType.ProductInfo>) results.values;
            if (results.count > 0) {
                initImage(tasklist);
                //getWare(tasklist);
                notifyDataSetChanged();
                notifyListeners(results.count, tasklist);
            } else {
                notifyListeners(0, tasklist);
                notifyDataSetInvalidated();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            // TODO Auto-generated method stub
            FilterResults filterResults = new FilterResults();

            if (mOriginalValues == null) {
                synchronized (mLock) {
                    //mOriginalValues = new ArrayList<>(tasklist);
                    Log.d("product", "App.mProductInfos" + App.mProductInfos.size());
                    mOriginalValues = new ArrayList<>(App.mProductInfos);//全部产品模糊搜索
                }
            }
            Log.d("product", "mOriginalValues" + mOriginalValues.size());
            if (prefix == null || prefix.length() == 0) {
                ArrayList<ShopTypeBean.ShopType.ProductInfo> list;
                synchronized (mLock) {
                    list = new ArrayList<>(mOriginalValues);
                }
                filterResults.values = list;
                filterResults.count = list.size();
                keyWrold = "";
            } else {
                String prefixString = prefix.toString().toLowerCase();
                ArrayList<ShopTypeBean.ShopType.ProductInfo> values;
                synchronized (mLock) {
                    values = new ArrayList<>(mOriginalValues);
                }

                final int count = values.size();
                final ArrayList<ShopTypeBean.ShopType.ProductInfo> newValues = new ArrayList<>();

                for (int i = 0; i < count; i++) {
                    ShopTypeBean.ShopType.ProductInfo value = values.get(i);
                    // First match against the whole, non-splitted value
                    boolean hasName = hasValue(value.getProductInfoName(), prefixString);
                    boolean hasId = hasValue(value.getProductInfoId(), prefixString);
                    boolean hasBar = hasValue(value.getProductBarCode(), prefixString);
                    boolean hasType = hasValue(value.getProductTypeName(), prefixString);
                    if (hasName || hasId || hasBar || hasType) {
                        newValues.add(value);
                        keyWrold = prefixString;
                    }
                }
                filterResults.values = newValues;
                filterResults.count = newValues.size();
                Log.d("product", "count:" + count);

            }
            return filterResults;
        }
    };

    private boolean hasValue(String productInfoName, String prefixString) {
        if (StringUtil.isEmpty(productInfoName)) {
            return false;
        } else {
            if (productInfoName.toLowerCase().contains(prefixString)) {
                return true;
            }
        }
        return false;
    }

    private void notifyListeners(int num, List<ShopTypeBean.ShopType.ProductInfo> tasklist) {
        updateListener.update(num , tasklist);
    }

    public interface UpdateCarListener {
        void update(int num, List<ShopTypeBean.ShopType.ProductInfo> tasklist);
    }

    public void setUpdateCarListener(UpdateCarListener updateListener) {
        this.updateListener = updateListener;
    }

    class Product extends AsyncTask<String, String, String> {
        List<ShopTypeBean.ShopType.ProductInfo> list;

        public Product(List<ShopTypeBean.ShopType.ProductInfo> type) {
            list = type;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                for (int i = 0; i < list.size(); i++) {
                    Log.d("product", "doInBackground:" + i + " " + list.size());
                    ShopTypeBean.ShopType.ProductInfo productInfo = list.get(i);
                    String imgURL = Utils.showImg(productInfo.getProductInfoId(), productInfo.getProductBarCode());
                    if (!StringUtil.isEmpty(imgURL)) {
                        productInfo.setIconUrl(imgURL);
                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            Log.d("Product", "onPostExecute " + list.size());
            //refresh(list);
            notifyDataSetChanged();
        }
    }

}